# -*- coding: UTF-8 -*-

# Version 1.1.1


import Tkinter as tk
from tkFileDialog import askopenfilename
from tkFileDialog import asksaveasfilename
from tkFileDialog import askdirectory
from struct import *
import urllib, os, os.path, easygui, urllib2, time, codecs, sys, xml.dom.minidom

try:
    import platform
    pf = True
except:
    pf = False

#modes: clf, wlan, blue, net_log, wlan_log, ''
#Globals
title = 'PyNetMony PC-Tool v1.1.1 - '
homedir = os.getcwd()+os.sep
stdoutfile = homedir+'stdout.log'

if os.path.isfile(stdoutfile):
    sys.stdout = open(stdoutfile, 'a')
else:
    sys.stdout = open(stdoutfile, 'w')
    if pf == True:
        print sys.platform+' '+platform.platform()
    print homedir+'\r\n'
#sys.stderr = open(homedir+'stderr.log', 'w')

helpfile = os.getcwd()+os.sep+'PyNetMony PC-Tool Help.chm'
database = ''
output_dir = ''
address = u''
mode = ''
mode_filter = 0
wlan_header = ''
clf_header = ''
bt_header = ''
wlog_header = ''
netlog_header = ''
kismet_header = ''
filename = ''
backup_list = []
second_db_imported = 0
listbox2 = 0
defaultencoding = 'utf-8'#'iso-8859-1'
traffic = 0.0

# KML-Globals
kml_header = [u'<?xml version="1.0" encoding="UTF-8"?>\r\n'\
          '<kml xmlns="http://earth.google.com/kml/2.2">\r\n'\
          '\t<Document>\r\n'\
          '\t\t<name>','</name>\r\n'] # name1
kml_path_style = u'\t\t<Style id="yellowLineGreenPoly">\r\n'\
          '\t\t\t<LineStyle>\r\n'\
          '\t\t\t\t<color>7f00ffff</color>\r\n'\
          '\t\t\t\t<width>4</width>\r\n'\
          '\t\t\t</LineStyle>\r\n'\
          '\t\t\t<PolyStyle>\r\n'\
          '\t\t\t\t<color>7f00ff00</color>\r\n'\
          '\t\t\t</PolyStyle>\r\n'\
          '\t\t</Style>\r\n'
kml_style = u'<StyleMap id="msn_wpa-pushpin">\r\n'\
        '\t\t<Pair>\r\n'\
        '\t\t\t\t<key>normal</key>\r\n'\
        '\t\t\t\t<styleUrl>#sn_wpa-pushpin</styleUrl>\r\n'\
        '\t\t</Pair>\r\n'\
        '\t\t<Pair>\r\n'\
        '\t\t\t\t<key>highlight</key>\r\n'\
        '\t\t\t\t<styleUrl>#sh_wpa-pushpin</styleUrl>\r\n'\
        '\t\t</Pair>\r\n'\
        '</StyleMap>\r\n'\
        '<Style id="sh_off-pushpin">\r\n'\
        '\t\t<IconStyle>\r\n'\
        '\t\t\t\t<color>ff00ff00</color>\r\n'\
        '\t\t\t\t<scale>0.5</scale>\r\n'\
        '\t\t\t\t<Icon>\r\n'\
        '\t\t\t\t\t\t<href>http://maps.google.com/mapfiles/kml/pal4/icon57.png</href>\r\n'\
        '\t\t\t\t</Icon>\r\n'\
        '\t\t\t\t<hotSpot x="10" y="2" xunits="pixels" yunits="pixels"/>\r\n'\
        '\t\t</IconStyle>\r\n'\
        '\t\t<ListStyle>\r\n'\
        '\t\t</ListStyle>\r\n'\
        '</Style>\r\n'\
        '<Style id="sn_off-pushpin">\r\n'\
        '\t\t<IconStyle>\r\n'\
        '\t\t\t\t<color>ff00ff00</color>\r\n'\
        '\t\t\t\t<scale>0.5</scale>\r\n'\
        '\t\t\t\t<Icon>\r\n'\
        '\t\t\t\t\t\t<href>http://maps.google.com/mapfiles/kml/pal4/icon57.png</href>\r\n'\
        '\t\t\t\t</Icon>\r\n'\
        '\t\t\t\t<hotSpot x="10" y="2" xunits="pixels" yunits="pixels"/>\r\n'\
        '\t\t</IconStyle>\r\n'\
        '\t\t<ListStyle>\r\n'\
        '\t\t</ListStyle>\r\n'\
        '</Style>\r\n'\
        '<Style id="sh_wpa-pushpin">\r\n'\
        '\t\t<IconStyle>\r\n'\
        '\t\t\t\t<color>ff0000ff</color>\r\n'\
        '\t\t\t\t<scale>0.5</scale>\r\n'\
        '\t\t\t\t<Icon>\r\n'\
        '\t\t\t\t\t\t<href>http://maps.google.com/mapfiles/kml/pal4/icon57.png</href>\r\n'\
        '\t\t\t\t</Icon>\r\n'\
        '\t\t\t\t<hotSpot x="10" y="2" xunits="pixels" yunits="pixels"/>\r\n'\
        '\t\t</IconStyle>\r\n'\
        '\t\t<ListStyle>\r\n'\
        '\t\t</ListStyle>\r\n'\
        '</Style>\r\n'\
        '<StyleMap id="msn_off-pushpin">\r\n'\
        '\t\t<Pair>\r\n'\
        '\t\t\t\t<key>normal</key>\r\n'\
        '\t\t\t\t<styleUrl>#sn_off-pushpin</styleUrl>\r\n'\
        '\t\t</Pair>\r\n'\
        '\t\t<Pair>\r\n'\
        '\t\t\t\t<key>highlight</key>\r\n'\
        '\t\t\t\t<styleUrl>#sh_off-pushpin</styleUrl>\r\n'\
        '\t\t</Pair>\r\n'\
        '</StyleMap>\r\n'\
        '<Style id="sn_wpa-pushpin">\r\n'\
        '\t\t<IconStyle>\r\n'\
        '\t\t\t\t<color>ff0000ff</color>\r\n'\
        '\t\t\t\t<scale>0.5</scale>\r\n'\
        '\t\t\t\t<Icon>\r\n'\
        '\t\t\t\t\t\t<href>http://maps.google.com/mapfiles/kml/pal4/icon57.png</href>\r\n'\
        '\t\t\t\t</Icon>\r\n'\
        '\t\t\t\t<hotSpot x="10" y="2" xunits="pixels" yunits="pixels"/>\r\n'\
        '\t\t</IconStyle>\r\n'\
        '\t\t<ListStyle>\r\n'\
        '\t\t</ListStyle>\r\n'\
        '</Style>\r\n'\
        '<StyleMap id="msn_wep-pushpin">\r\n'\
        '\t\t<Pair>\r\n'\
        '\t\t\t\t<key>normal</key>\r\n'\
        '\t\t\t\t<styleUrl>#sn_wep-pushpin</styleUrl>\r\n'\
        '\t\t</Pair>\r\n'\
        '\t\t<Pair>\r\n'\
        '\t\t\t\t<key>highlight</key>\r\n'\
        '\t\t\t\t<styleUrl>#sh_wep-pushpin</styleUrl>\r\n'\
        '\t\t</Pair>\r\n'\
        '</StyleMap>\r\n'\
        '<Style id="sn_wep-pushpin">\r\n'\
        '\t\t<IconStyle>\r\n'\
        '\t\t\t\t<color>ff00ffff</color>\r\n'\
        '\t\t\t\t<scale>0.5</scale>\r\n'\
        '\t\t\t\t<Icon>\r\n'\
        '\t\t\t\t\t\t<href>http://maps.google.com/mapfiles/kml/pal4/icon57.png</href>\r\n'\
        '\t\t\t\t</Icon>\r\n'\
        '\t\t\t\t<hotSpot x="10" y="2" xunits="pixels" yunits="pixels"/>\r\n'\
        '\t\t</IconStyle>\r\n'\
        '\t\t<ListStyle>\r\n'\
        '\t\t</ListStyle>\r\n'\
        '</Style>\r\n'\
        '<Style id="sh_wep-pushpin">\r\n'\
        '\t\t<IconStyle>\r\n'\
        '\t\t\t\t<color>ff00ffff</color>\r\n'\
        '\t\t\t\t<scale>0.5</scale>\r\n'\
        '\t\t\t\t<Icon>\r\n'\
        '\t\t\t\t\t\t<href>http://maps.google.com/mapfiles/kml/pal4/icon57.png</href>\r\n'\
        '\t\t\t\t</Icon>\r\n'\
        '\t\t\t\t<hotSpot x="10" y="2" xunits="pixels" yunits="pixels"/>\r\n'\
        '\t\t</IconStyle>\r\n'\
        '\t\t<ListStyle>\r\n'\
        '\t\t</ListStyle>\r\n'\
        '</Style>\r\n'
kml_open_folder = [
        u'<Folder>\r\n'\
        '<name>',u'</name>\r\n'] #name2
kml_close_folder = u'</Folder>\r\n'
kml_placemark = [
        u"\t<Placemark>\r\n"\
        "\t\t<description>",u"</description>\r\n"\
        "\t\t<name></name>\r\n"\
        "\t\t<LookAt>\r\n"\
        "\t\t\t\t<longitude>",u"</longitude>\r\n"\
        "\t\t\t\t<latitude>",u"</latitude>\r\n"\
        "\t\t\t\t<range>200</range>\r\n"\
        "\t\t\t\t<tilt>0</tilt>\r\n"\
        "\t\t\t\t<heading>0</heading>\r\n"\
        "\t\t</LookAt>\r\n"\
        "\t\t<styleUrl>#",u"</styleUrl>\r\n" 
        "\t\t<Point>\r\n"\
        "\t\t\t<coordinates>",u",",u"</coordinates>\r\n"\
        "\t\t</Point>\r\n"\
        "\t</Placemark>\r\n"]
kml_path_placemark_s = [u'\t\t<Placemark>\r\n'\
          '\t\t\t<name>',u'</name>\r\n'\
          '\t\t\t<description>The hight of the path indicates the signalstrenth.</description>\r\n'\
          '\t\t\t<styleUrl>#yellowLineGreenPoly</styleUrl>\r\n'\
          '\t\t\t<LineString>\r\n'\
          '\t\t\t<extrude>1</extrude>\r\n'\
          '\t\t\t<tessellate>0</tessellate>\r\n'\
          '\t\t\t\t<altitudeMode>relativeToGround</altitudeMode>\r\n'\
          '\t\t\t\t<coordinates>\r\n']
kml_path_placemark_e = u'\t\t\t\t</coordinates>\r\n'\
          '\t\t\t</LineString>\r\n'\
          '\t\t</Placemark>\r\n'
kml_footer = u'\t</Document>\r\n'\
          '</kml>\r\n'
coordinates = []

# MyLocation Globals
url = 'http://www.google.com/glm/mmap'

class ToolTip:
    def __init__(self, master, text='Your text here', delay=1500, **opts):
        self.master = master
        self._opts = {'anchor':'center', 'bd':1, 'bg':'lightyellow', 'delay':delay, 'fg':'black',\
                      'follow_mouse':0, 'font':None, 'justify':'left', 'padx':4, 'pady':2,\
                      'relief':'solid', 'state':'normal', 'text':text, 'textvariable':None,\
                      'width':0, 'wraplength':150}
        self.configure(**opts)
        self._tipwindow = None
        self._id = None
        self._id1 = self.master.bind("<Enter>", self.enter, '+')
        self._id2 = self.master.bind("<Leave>", self.leave, '+')
        self._id3 = self.master.bind("<ButtonPress>", self.leave, '+')
        self._follow_mouse = 0
        if self._opts['follow_mouse']:
            self._id4 = self.master.bind("<Motion>", self.motion, '+')
            self._follow_mouse = 1

    def configure(self, **opts):
        for key in opts:
            if self._opts.has_key(key):
                self._opts[key] = opts[key]
            else:
                KeyError = 'KeyError: Unknown option: "%s"' %key
                raise KeyError

    ##----these methods handle the callbacks on "<Enter>", "<Leave>" and "<Motion>"---------------##
    ##----events on the parent widget; override them if you want to change the widget's behavior--##

    def enter(self, event=None):
        self._schedule()

    def leave(self, event=None):
        self._unschedule()
        self._hide()

    def motion(self, event=None):
        if self._tipwindow and self._follow_mouse:
            x, y = self.coords()
            self._tipwindow.wm_geometry("+%d+%d" % (x, y))

    ##------the methods that do the work:---------------------------------------------------------##

    def _schedule(self):
        self._unschedule()
        if self._opts['state'] == 'disabled':
            return
        self._id = self.master.after(self._opts['delay'], self._show)

    def _unschedule(self):
        id = self._id
        self._id = None
        if id:
            self.master.after_cancel(id)

    def _show(self):
        if self._opts['state'] == 'disabled':
            self._unschedule()
            return
        if not self._tipwindow:
            self._tipwindow = tw = tk.Toplevel(self.master)
            # hide the window until we know the geometry
            tw.withdraw()
            tw.wm_overrideredirect(1)

            if tw.tk.call("tk", "windowingsystem") == 'aqua':
                tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "none")

            self.create_contents()
            tw.update_idletasks()
            x, y = self.coords()
            tw.wm_geometry("+%d+%d" % (x, y))
            tw.deiconify()

    def _hide(self):
        tw = self._tipwindow
        self._tipwindow = None
        if tw:
            tw.destroy()

    ##----these methods might be overridden in derived classes:----------------------------------##

    def coords(self):
        # The tip window must be completely outside the master widget;
        # otherwise when the mouse enters the tip window we get
        # a leave event and it disappears, and then we get an enter
        # event and it reappears, and so on forever :-(
        # or we take care that the mouse pointer is always outside the tipwindow :-)
        tw = self._tipwindow
        twx, twy = tw.winfo_reqwidth(), tw.winfo_reqheight()
        w, h = tw.winfo_screenwidth(), tw.winfo_screenheight()
        # calculate the y coordinate:
        if self._follow_mouse:
            y = tw.winfo_pointery() + 20
            # make sure the tipwindow is never outside the screen:
            if y + twy > h:
                y = y - twy - 30
        else:
            y = self.master.winfo_rooty() + self.master.winfo_height() + 3
            if y + twy > h:
                y = self.master.winfo_rooty() - twy - 3
        # we can use the same x coord in both cases:
        x = tw.winfo_pointerx() - twx / 2
        if x < 0:
            x = 0
        elif x + twx > w:
            x = w - twx
        return x, y

    def create_contents(self):
        opts = self._opts.copy()
        for opt in ('delay', 'follow_mouse', 'state'):
            del opts[opt]
        label = tk.Label(self._tipwindow, **opts)
        label.pack()

def path_kml():
    global mode, filename
    try:
        if mode == 'net_log':
            filepath = asksaveasfilename(defaultextension='.kml',initialfile=filename+'.kml',filetypes=[("KML-file","*.kml")])
        elif mode == 'wlan_log':
            filepath = asksaveasfilename(defaultextension='.kml',initialfile=filename+'.kml',filetypes=[("KML-file","*.kml")])
        if len(filepath) > 0:
            if mode == 'net_log':
                data = make_path_kml(9,10,8,filepath)
            elif mode == 'wlan_log':
                data = make_path_kml(6,5,4,filepath)
            file = open(filepath,"wb")
            for i in range(len(data)):
                file.write(data[i])
            file.close()
            easygui.msgbox(msg="KML-Export successful", title="Info", ok_button="OK")
        else:
            pass
    except BaseException, err:
        print time.ctime()+': path_kml: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def make_path_kml(lon_col,lat_col,rxl_col,filepath):
    global kml_header, kml_path_style, kml_path_placemark_s, kml_path_placemark_e, coordinates, kml_footer, mode
    try:
        kml = []
        name = filepath[filepath.rfind('/')+1:]
        kml.insert(0,(kml_header[0]+name+kml_header[1]+kml_path_style))
        coordinates = []
        name2 = filepath[filepath.rfind('/')+1:-4].replace('_',' ').title()
        spots = make_list(0)
        del spots[0]
        total = len(spots)
        last_cid = ''
        for i in range(total):
            spotlist = spots[i].split(';')
            if mode == 'net_log' and len(spotlist) > 12 and spotlist[10] <> 'n/a':
                if i < 1:
                    coordinates.append(kml_path_placemark_s[0]+'CID: '+str(spotlist[2])+kml_path_placemark_s[1])
                elif i > 0 and spotlist[2] <> last_cid:
                    coordinates.append(kml_path_placemark_e)
                    coordinates.append(kml_path_placemark_s[0]+'CID: '+str(spotlist[2])+kml_path_placemark_s[1])
                coordinates.append('\t\t\t\t  '+str(spotlist[lon_col])+','+str(spotlist[lat_col])+','+str(int(spotlist[rxl_col])+111)+'\r\n')
                last_cid = spotlist[2]
            elif mode=='wlan_log' and len(spotlist) > 6 and spotlist[5] <> 'n/a':
                if i < 1:
                    coordinates.append(kml_path_placemark_s[0]+name2+kml_path_placemark_s[1])
                spotlist[lon_col] = spotlist[lon_col][:-2] 
                coordinates.append('\t\t\t\t  '+str(spotlist[lon_col])+','+str(spotlist[lat_col])+','+str(int(spotlist[rxl_col])+111)+'\r\n')
        for line in coordinates:
            kml.append(line)
        kml.append(kml_path_placemark_e)
        kml.append(kml_footer)
        return kml
    except BaseException, err:
        print time.ctime()+': make_path_kml: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def make_kml(filepath,crypt = ''):
    global kml_header, kml_style, kml_open_folder, kml_close_folder, kml_footer, mode, defaultencoding
    try:
        kml = []
        name = filepath[filepath.rfind('/')+1:]
        name2 = filepath[filepath.rfind('/')+1:-4].replace('_',' ').title()
        kml.insert(0,(kml_header[0]+name+kml_header[1]+kml_style+kml_open_folder[0]+name2+kml_open_folder[1]))
        liste = make_list(0)
        placemarks = []
        del liste[0]
        total = len(liste)
        for i in range(total):
            placemark = liste[i].split(';')
            if mode == 'clf' and (len(placemark) > 8) and (placemark[4] <> ''):
                ssid = is_not_control(placemark[7])
                placemarks.append(add_placemark(placemark[4],placemark[5],0.0,ssid+'\r\nMCC: '+placemark[0][:3]+'\r\nMNC: '+placemark[0][3:]+'\r\nCID: '+placemark[1]+'\r\nLAC: '+placemark[2], "msn_wpa-pushpin"))
            elif mode == 'blue' and (len(placemark) > 7) and (placemark[1] <> 'NaN'):
                ssid = is_not_control(placemark[3])
                placemarks.append(add_placemark(placemark[1],placemark[2],0.0,ssid+'\r\nClass: '+placemark[7], "msn_wpa-pushpin"))
            elif mode == 'wlan' and (len(placemark) > 9) and (placemark[1] <> 'NaN') and placemark[4] == crypt and crypt == 'Open':
                placemark[3] = placemark[3].replace('<',"(")
                placemark[3] = placemark[3].replace('>',")")
                placemark[3] = placemark[3].replace('&',"and")
                ssid = is_not_control(placemark[3])#.encode(defaultencoding)#umlaut_converter(is_not_control(placemark[3]))
                placemarks.append(add_placemark(placemark[1],placemark[2],0.0,ssid+"\r\n"+placemark[0]+"\r\n"+placemark[4], "msn_off-pushpin"))
            elif mode == 'wlan' and (len(placemark) > 9) and (placemark[1] <> 'NaN') and placemark[4] == crypt and crypt == 'Wep':
                placemark[3] = placemark[3].replace('<',"(")
                placemark[3] = placemark[3].replace('>',")")
                placemark[3] = placemark[3].replace('&',"and")
                ssid = is_not_control(placemark[3])#.encode(defaultencoding)#umlaut_converter(is_not_control(placemark[3]))
                placemarks.append(add_placemark(placemark[1],placemark[2],0.0,ssid+"\r\n"+placemark[0]+"\r\n"+placemark[4], "msn_wep-pushpin"))
            elif mode == 'wlan' and (len(placemark) > 9) and (placemark[1] <> 'NaN') and placemark[4] == crypt and crypt == 'WpaPsk':
                placemark[3] = placemark[3].replace('<',"(")
                placemark[3] = placemark[3].replace('>',")")
                placemark[3] = placemark[3].replace('&',"and")
                ssid = is_not_control(placemark[3])#.encode(defaultencoding)#umlaut_converter(is_not_control(placemark[3]))
                placemarks.append(add_placemark(placemark[1],placemark[2],0.0,ssid+"\r\n"+placemark[0]+"\r\n"+placemark[4], "msn_wpa-pushpin"))
            elif mode == 'kismet' and (len(placemark) > 9) and (placemark[32].find('Na') == -1) and placemark[7] == crypt and crypt == 'None':
                placemark[2] = placemark[2].replace('<',"(")
                placemark[2] = placemark[2].replace('>',")")
                placemark[2] = placemark[2].replace('&',"and")
                ssid = is_not_control(placemark[2])#.encode(defaultencoding)#umlaut_converter(is_not_control(placemark[3]))
                placemarks.append(add_placemark(placemark[32],placemark[33],0.0,ssid+"\r\n"+placemark[3]+"\r\n"+placemark[7], "msn_off-pushpin"))
            elif mode == 'kismet' and (len(placemark) > 9) and (placemark[32].find('Na') == -1) and placemark[7] == crypt and crypt == 'Wep':
                placemark[2] = placemark[2].replace('<',"(")
                placemark[2] = placemark[2].replace('>',")")
                placemark[2] = placemark[2].replace('&',"and")
                ssid = is_not_control(placemark[2])#.encode(defaultencoding)#umlaut_converter(is_not_control(placemark[3]))
                placemarks.append(add_placemark(placemark[32],placemark[33],0.0,ssid+"\r\n"+placemark[3]+"\r\n"+placemark[7], "msn_wep-pushpin"))
            elif mode == 'kismet' and (len(placemark) > 9) and (placemark[32].find('Na') == -1) and placemark[7] == crypt and crypt == 'WpaPsk':
                placemark[2] = placemark[2].replace('<',"(")
                placemark[2] = placemark[2].replace('>',")")
                placemark[2] = placemark[2].replace('&',"and")
                ssid = is_not_control(placemark[2])#.encode(defaultencoding)#umlaut_converter(is_not_control(placemark[3]))
                placemarks.append(add_placemark(placemark[32],placemark[33],0.0,ssid+"\r\n"+placemark[3]+"\r\n"+placemark[7], "msn_wpa-pushpin"))
        for line in placemarks:
            kml.append(line)
        kml.append(kml_close_folder)
        kml.append(kml_footer)
        return kml
    except BaseException, err:
        print time.ctime()+': make_kml: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def add_placemark(latitude, longitude, altitude = 0.0, description = " ", style = "msn_wep-pushpin", range = 6000, tilt = 45, heading = 0):
    global kml_placemark
    try:
        placemark = unicode(kml_placemark[0]+description+kml_placemark[1]+str(longitude)+kml_placemark[2]+str(latitude)+kml_placemark[3]+style+kml_placemark[4]+str(longitude)+kml_placemark[5]+str(latitude)+kml_placemark[6])
        return placemark
    except BaseException, err:
        print time.ctime()+': add_placemark: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def export_kml(event = '<Control-KeyPress-k>'):
    global mode, filename, defaultencoding
    try:
        data = []
        if mode == 'wlan' or mode == 'clf' or mode == 'blue' or mode == 'kismet':
            if mode == 'wlan':
                filepath = asksaveasfilename(defaultextension='.kml',initialfile='pynetmony_open_wlan_pc.kml',filetypes=[("KML-file","*.kml")])
                if len(filepath) >0:
                    data = make_kml(filepath,'Open')
                    fileo = codecs.open(filepath,"wb",defaultencoding)
                    for i in range(len(data)):
                        fileo.write(data[i])
                    fileo.close()
                else:
                    pass
                filepath = asksaveasfilename(defaultextension='.kml',initialfile='pynetmony_wep_wlan_pc.kml',filetypes=[("KML-file","*.kml")])
                if len(filepath) >0:
                    data = make_kml(filepath,'Wep')
                    fileo = codecs.open(filepath,"wb",defaultencoding)
                    for i in range(len(data)):
                        fileo.write(data[i])
                    fileo.close()
                else:
                    pass
                filepath = asksaveasfilename(defaultextension='.kml',initialfile='pynetmony_wpa_wlan_pc.kml',filetypes=[("KML-file","*.kml")])
                if len(filepath) >0:
                    data = make_kml(filepath,'WpaPsk')
                    fileo = codecs.open(filepath,"wb",defaultencoding)
                    for i in range(len(data)):
                        fileo.write(data[i])
                    fileo.close()
                    easygui.msgbox(msg="KML-Export successful", title="Info", ok_button="OK")
                else:
                    pass
            elif mode == 'kismet':
                filepath = asksaveasfilename(defaultextension='.kml',initialfile='kismet_open.kml',filetypes=[("KML-file","*.kml")])
                if len(filepath) >0:
                    data = make_kml(filepath,'None')
                    fileo = codecs.open(filepath,"wb",defaultencoding)
                    for i in range(len(data)):
                        fileo.write(data[i])
                    fileo.close()
                else:
                    pass
                filepath = asksaveasfilename(defaultextension='.kml',initialfile='kismet_wep.kml',filetypes=[("KML-file","*.kml")])
                if len(filepath) >0:
                    data = make_kml(filepath,'Wep')
                    fileo = codecs.open(filepath,"wb",defaultencoding)
                    for i in range(len(data)):
                        fileo.write(data[i])
                    fileo.close()
                else:
                    pass
                filepath = asksaveasfilename(defaultextension='.kml',initialfile='kismet_wpa.kml',filetypes=[("KML-file","*.kml")])
                if len(filepath) >0:
                    data = make_kml(filepath,'WpaPsk')
                    fileo = codecs.open(filepath,"wb",defaultencoding)
                    for i in range(len(data)):
                        fileo.write(data[i])
                    fileo.close()
                    easygui.msgbox(msg="KML-Export successful", title="Info", ok_button="OK")
                else:
                    pass
            else:
                filepath = ''
                if mode == 'clf':
                    filepath = asksaveasfilename(defaultextension='.kml',initialfile=filename+'.kml',filetypes=[("KML-file","*.kml")])
                elif mode == 'blue':
                    filepath = asksaveasfilename(defaultextension='.kml',initialfile=filename+'.kml',filetypes=[("KML-file","*.kml")])
                if len(filepath) > 0:
                    if mode == 'clf':
                        data = make_kml(filepath)
                    elif mode == 'blue':
                        data = make_kml(filepath)
                    fileo = codecs.open(filepath,"wb",defaultencoding)
                    for i in range(len(data)):
                        fileo.write(data[i])
                    fileo.close()
                    easygui.msgbox(msg="KML-Export successful", title="Info", ok_button="OK")
                else:
                    pass
        else:
            path_kml()
    except BaseException, err:
        print time.ctime()+': export_kml: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def is_not_control(input_v):
    strin = ""
    try:
        for zeichen in input_v:
            c = ord(zeichen)
            if not c < 32 or (126 < c < 160):
                strin += zeichen
        return strin
    except BaseException, err:
        print time.ctime()+': is_not_control: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def fill_spaces(input_s):
    strin = ''
    try:
        for zeichen in input_s:
            if zeichen == ' ':
                zeichen = '%20'
            else:
                zeichen = zeichen
            strin += zeichen
        return strin
    except BaseException, err:
        print time.ctime()+': fill_spaces: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def umlaut_converter(inputv):
    strin = ''
    try:
        for zeichen in inputv:
            if zeichen == chr(252):
                zeichen = 'ue'
            elif zeichen == chr(246):
                zeichen = 'oe'
            elif zeichen == chr(228):
                zeichen = 'ae'
            elif zeichen == chr(223):
                zeichen = 'ss'
            elif zeichen == chr(39):
                zeichen = ''
            elif zeichen == chr(242):
                zeichen = 'o'
            elif ord(zeichen) > 128:
                zeichen = ' '
            else:
                zeichen = zeichen
            strin += zeichen
        return strin
    except BaseException, err:
        print time.ctime()+': umlaut_converter: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def kismet_export():
    global mode, defaultencoding
    kismet_list = []
    try:
        if mode == 'wlan':
            wlan_list = make_list(0)
            del wlan_list[0]
            fileout = asksaveasfilename(defaultextension='.csv',initialfile='PyNetMony_Kismet_'+time.strftime("%Y_%m_%d")+'_all.csv',filetypes=[("CSV-file","*.csv")])
            if fileout == '':
                pass
            else:
                file = open(fileout,'wb')
                header = u'Network;NetType;ESSID;BSSID;Info;Channel;Cloaked;Encryption;Decrypted;MaxRate;MaxSeenRate;Beacon;LLC;Data;Crypt;Weak;Total;Carrier;Encoding;FirstTime;LastTime;BestQuality;BestSignal;BestNoise;GPSMinLat;GPSMinLon;GPSMinAlt;GPSMinSpd;GPSMaxLat;GPSMaxLon;GPSMaxAlt;GPSMaxSpd;GPSBestLat;GPSBestLon;GPSBestAlt;DataSize;IPType;IP;'+chr(13)+chr(10)
                kismet_list.append(header)
                total = len(wlan_list)
                for i in range(total):
                    wlist = wlan_list[i].split(';')
                    if (len(wlist) > 9):
                        if wlist[6] == 'Infra':
                            wlist[6] = u'infrastructure'
                        if wlist[4] == 'Open':
                            wlist[4] = u'None'
                        if wlist[1] == 'NaN':
                            wlist[1] = wlist[2] = u'0'
                        if wlist[3].count('<no ssid>') > 0:
                            wlist[3] = u'<no ssid>'
                        y = int(wlist[9][:4])
                        mo = int(wlist[9][5:7])
                        d = int(wlist[9][-2:])
                        h = int(wlist[10][:2])
                        mi =int(wlist[10][3:5])
                        s = int(wlist[10][6:8])
                        at = time.asctime((y,mo,d,h,mi,s,0,0,-1))
                        at = at[:-1]
                        #print i # to find invalid line
                        line = str(i+1)+u';'+wlist[6]+u';'+is_not_control(wlist[3])+u';'+wlist[0]+u';;'+wlist[7]+u';None;'+wlist[4]+u';No;0;0;'+wlist[5]+u';;;;;;;;'+str(at)+u';'+str(at)+u';0;'+wlist[8]+u';;;;;;;;;;'+wlist[1]+u';'+wlist[2]+u';;;None;0.0.0.0;'+str(chr(13))+str(chr(10))
                        kismet_list.append(line.encode(defaultencoding))
                file.writelines(kismet_list)
                file.close()
                kismet_list = []
                easygui.msgbox(msg="Kismet-Export successful", title="Info", ok_button="OK")
        else:
            easygui.msgbox(msg="Open a WLAN-database to export to Kismet!", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': kismet_export: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")
    
def kismet_export_today():
    global wlan_list, mode
    kismet_list = []
    counter = 0
    date = easygui.enterbox(msg='Enter date to export.\nFormat is: YYYY_MM_DD!', title='Enter date to export!', default=time.strftime("%Y_%m_%d"), strip=True)
    try:
        if date <> None:
            if mode == 'wlan':
                wlan_list = make_list(0)
                del wlan_list[0]
                fileout = asksaveasfilename(defaultextension='.csv',initialfile='PyNetMony_Kismet_'+date+'.csv',filetypes=[("CSV-file","*.csv"),("All files","*")])
                if fileout == '':
                    pass
                else:
                    file = open(fileout,'wb')
                    header = u'Network;NetType;ESSID;BSSID;Info;Channel;Cloaked;Encryption;Decrypted;MaxRate;MaxSeenRate;Beacon;LLC;Data;Crypt;Weak;Total;Carrier;Encoding;FirstTime;LastTime;BestQuality;BestSignal;BestNoise;GPSMinLat;GPSMinLon;GPSMinAlt;GPSMinSpd;GPSMaxLat;GPSMaxLon;GPSMaxAlt;GPSMaxSpd;GPSBestLat;GPSBestLon;GPSBestAlt;DataSize;IPType;IP;'+chr(13)+chr(10)
                    kismet_list.append(header)
                    total = len(wlan_list)
                    for i in range(total):
                        wlist = wlan_list[i].split(';')
                        if (len(wlist) > 9) and (wlist[9]==unicode(date.replace('_','/'))):
                            counter += 1
                            if wlist[6] == 'Infra':
                                wlist[6] = u'infrastructure'
                            if wlist[4] == 'Open':
                                wlist[4] = u'None'
                            if wlist[1] == 'NaN':
                                wlist[1] = wlist[2] = u'0'
                            if wlist[3].count('<no ssid>') > 0:
                                wlist[3] = u'<no ssid>'
                            y = int(wlist[9][:4])
                            mo = int(wlist[9][5:7])
                            d = int(wlist[9][-2:])
                            h = int(wlist[10][:2])
                            mi =int(wlist[10][3:5])
                            s = int(wlist[10][6:8])
                            at = time.asctime((y,mo,d,h,mi,s,0,0,-1))
                            at = at[:-1]
                            line = str(counter)+u';'+wlist[6]+u';'+is_not_control(wlist[3])+u';'+wlist[0]+u';;'+wlist[7]+u';None;'+wlist[4]+u';No;0;0;'+wlist[5]+u';;;;;;;;'+str(at)+u';'+str(at)+u';0;'+wlist[8]+u';;;;;;;;;;'+wlist[1]+u';'+wlist[2]+u';;;None;0.0.0.0;'+chr(13)+chr(10)
                            kismet_list.append(line.encode(defaultencoding))
                    file.writelines(kismet_list)
                    file.close()
                    easygui.msgbox(msg="Kismet-Export successful", title="Info", ok_button="OK")
                    kismet_list = []
            else:
                easygui.msgbox(msg="Open a WLAN-database to export to Kismet!", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': kismet_export_today: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def add_item():
    """
    add the text in the Entry widget to the end of the listbox
    """
    global mode_filter, backup_list
    try:
        if mode_filter == 0:
            listbox1.insert(tk.END, enter1.get())
            backup_list = list(listbox1.get(0,tk.END))
        else:
            easygui.msgbox(msg="Filtered Databases can't be edited at the moment.", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': add_item: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def delete_item(event):
    """
    delete a selected line from the listbox
    """
    global mode_filter
    try:
        # get selected line index
        index = listbox1.curselection()[0]
        if index == '0':
            pass
        else:
            if mode_filter == 0:
                listbox1.delete(index)
            else:
                easygui.msgbox(msg="Filtered Databases can't be edited at the moment.", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': delete_item: '+str(err)
        pass
 
def get_list(event):
    """
    function to read the listbox selection
    and put the result in an entry widget
    """
    try:
        if listbox1.size() > 0:
            # get selected line index
            index = listbox1.curselection()[0]
            # get the line's text
            seltext = listbox1.get(index)
            # delete previous text in enter1
            enter1.delete(0, 165)
            # now display the selected text
            enter1.insert(0, seltext)
        else:
            easygui.msgbox(msg="You have to open a database first!", title="Error!", ok_button="OK")
        labels('<Button-1>')
    except BaseException, err:
        print time.ctime()+': get_list: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def set_list(event):
    """
    insert an edited line from the entry widget
    back into the listbox
    """
    global mode_filter, backup_list
    try:
        if mode_filter == 0:
            try:
                index = listbox1.curselection()[0]
                # delete old listbox line
                listbox1.delete(index)
            except IndexError:
                index = tk.END
            # insert edited item back into listbox1 at index
            listbox1.insert(index, enter1.get())
            backup_list = list(listbox1.get(0,tk.END))
        else:
            easygui.msgbox(msg="Filtered Databases can't be edited at the moment.", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': set_list: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def sort_list():
    """
    function to sort listbox items case insensitive
    """
    try:
        temp_list = list(listbox1.get(0, tk.END))
        temp_list.sort()#lambda x, y: cmp(x.lower(), y.lower()))
        # delete contents of present listbox
        listbox1.delete(0, tk.END)
        # load listbox with sorted data
        for item in temp_list:
            listbox1.insert(tk.END, item)
    except BaseException, err:
        print time.ctime()+': sort_list: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def filter_wlan(bereich,filter):
    global backup_list, mode, mode_filter
    try:
        if len(backup_list) <> 0:
            if mode == 'wlan' and filter <> -1:
                listbox1.delete(0, tk.END)
                for i in range(len(backup_list)):
                    listbox1.insert(i,backup_list[i])
                header = listbox1.get(0)
                listbox1.delete(0)
                liste = list(listbox1.get(0,tk.END))
                liste2 = []
                for i in range(len(liste)):
                    if liste[i][bereich[0]:bereich[1]].find(filter) > -1:
                        liste2.append(liste[i])
                del liste
                liste2.insert(0,header)
                # delete contents of present listbox
                listbox1.delete(0, tk.END)
                # load listbox with sorted data
                for i in range(len(liste2)):
                    listbox1.insert(i, liste2[i])
                if filter == ' ':
                    mode_filter = 0
                else:
                    mode_filter = 1
            else:
                mode_filter = 0
                easygui.msgbox(msg="Currently only WLAN-databases can be filtered!", title="Error!", ok_button="OK")
        else:
            backup_list = list(listbox1.get(0,tk.END))
            filter_wlan(filter)
    except BaseException, err:
        print time.ctime()+': filter_wlan: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")
        pass
            

def make_list(second=0):
    # get a list of listbox lines
    global mode, clf_header, wlan_header, kismet_header
    try:
        if second == 1:
            liste = list(listbox2.get(0, tk.END))
        else:
            liste = list(listbox1.get(0, tk.END))
        liste2 = []
        if mode == 'clf':
            liste[0] = clf_header
        elif mode == 'wlan':
            liste[0] = wlan_header
        elif mode == 'net_log':
            liste[0] = netlog_header
        elif mode == 'wlan_log':
            liste[0] = wlog_header
        elif mode == 'blue':
            liste[0] = bt_header
        elif mode == 'kismet':
            liste[0] = kismet_header
        #counter = 0
        for line in liste:
            line = line.replace(' | ',';')
            #counter += 1
            liste2.append(line.split(';'))
        #print str(counter)+' (make_list - counter)\r\n'
        #counter = 0
    #    liste = [line.replace('|',';') for line in liste]
    #    liste2 = [line.split(';') for line in liste]
        for i in range(len(liste2)):
            # delete whitespace
            liste2[i] = [item.rstrip() for item in liste2[i]]
            #liste2[i] = [item.lstrip() for item in liste2[i]]
            if mode == 'clf':
                if len(liste2[i]) > 1:
                    if liste2[i][4] == 'NaN':
                        liste2[i][4] = ''
                    if liste2[i][5] == 'NaN':
                        liste2[i][5] = ''
            liste2[i] = ';'.join(liste2[i])
        del liste
        # add newline 
        liste2 = [item + '\r\n' for item in liste2]
        return liste2
    except BaseException, err:
        print time.ctime()+': make_list: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def save_list(event):
    """
    save the current listbox contents to a file
    """
    global mode, filename, defaultencoding
    if mode <> '':
        try:
            if mode == 'wlan':
                try:
                    sort_list()
                except BaseException, err:
                    print time.ctime()+': save_list - sort_list(): '+str(err)
                    easygui.msgbox(msg="Couldn't sort list! Check stdout.log file!", title="Error!", ok_button="OK")
                temp_list = make_list(0)
            else:
                temp_list = make_list(0)
            if mode == 'clf':
                try:
                    fileout = asksaveasfilename(defaultextension='.clf',initialfile=filename+'.clf',filetypes=[("CLF-file","*.clf"),("All files","*")])
                    if fileout == '':
                        pass
                    else:
                        #fout = open(fileout, "wb")
                        fout = codecs.open(fileout, "wb", defaultencoding)
                        fout.writelines(temp_list)
                        fout.close()
                        easygui.msgbox(msg="File successfully saved", title="File Saved", ok_button="OK")
                except BaseException, err:
                    print time.ctime()+': save_list: '+str(err)
                    easygui.msgbox(msg="File not saved. Check stdout.log file!", title="Error!", ok_button="OK")
            else:
                try:
                    fileout = asksaveasfilename(defaultextension='.txt',initialfile=filename+'.txt',filetypes=[("Textfile","*.txt"),("All files","*")])
                    if fileout == '':
                        pass
                    else:
                        fout = codecs.open(fileout, "wb", defaultencoding)
                        fout.writelines(temp_list)
                        fout.close()
                        easygui.msgbox(msg="File successfully saved", title="File Saved", ok_button="OK")
                except BaseException, err:
                    print time.ctime()+': save_list: '+str(err)
                    easygui.msgbox(msg="File not saved. Check stdout.log file!", title="Error!", ok_button="OK")
        except BaseException, err:
            print time.ctime()+': save_list: '+str(err)
            easygui.msgbox(msg="You have to open a file first before you can save it...", title="Error!", ok_button="OK")
    else:
        easygui.msgbox(msg="Unknown filetypes can't be saved", title="Error!", ok_button="OK")

def binaere_suche(liste, eingabe):
    try:
        maxindex = len(liste) - 1
        suche_erfolgreich = False
        index = 0
        while not suche_erfolgreich and index <= maxindex:
            mitte = index + ((maxindex - index)/2)
            if liste[mitte][:17] == eingabe:
                suche_erfolgreich = True
            elif eingabe < liste[mitte][:17]:
                maxindex = mitte - 1
            else:
                index = mitte + 1
        if suche_erfolgreich:
            return mitte
        else:
            return -1
    except BaseException, err:
        print time.ctime()+': binaere_suche: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def merge():
    global wlan_header, mode_filter, backup_list
    try:
        if mode_filter == 0:
            counter = 0
            liste1 = make_list(0)
            liste2 = make_list(1)
            liste3 = []
            del liste1[0]
            del liste2[0]
            liste2 = [line.split(';') for line in liste2]
            for i in range(len(liste2)):
                index = binaere_suche(liste1, liste2[i][0])
                if index == -1:
                    liste3.append(liste2[i])
            for i in range(len(liste3)):
                liste1.append(';'.join(liste3[i]))
                counter += 1
            liste1.insert(0,wlan_header)
            aps = convert_list_2_text(liste1)
            count = listbox1.size()
            listbox1.delete(0,count)
            # load the listbox with data
            for item in aps:
                listbox1.insert(tk.END,' | '.join(item))
            backup_list = list(listbox1.get(0,tk.END))
            easygui.msgbox(msg="%i APs have been appended to your WLAN-database\nSort the database to append further APs." %counter, title="Info", ok_button="OK")
        else:
            easygui.msgbox(msg="Databases can't be merged when primary database is filtered!", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': merge: '+str(err)
        easygui.msgbox(msg="Databases could not be merged!", title="Error!", ok_button="OK")

def open_second_file():
    global second_db_imported, listbox2, mode
    if mode == 'wlan' and second_db_imported == 0:
        try:
            database = askopenfilename(filetypes=[("All files","*"),("Textfiles","*.txt"),("CLF-files","*.clf")])
            if len(database) > 0:
                second_db_imported = 1
                sec_db()
                count = listbox2.size()
                listbox2.delete(0,count)
                aps = read_data(database)
                # load the listbox with data
                for item in aps:
                    listbox2.insert(tk.END, ' | '.join(item))
                labels('<Button-1>')
            else:
              second_db_imported = 0  
        except BaseException, err:
            print time.ctime()+': open_second_file: '+str(err)
            second_db_imported = 0
    else:
        easygui.msgbox(msg="Open a primary WLAN-database first!", title="Error!", ok_button="OK")

def sec_db(close=0):
    global second_db_imported, listbox2, yscroll2, xscroll2
    if second_db_imported == 1:
        listbox2.grid(row=9, column=0, columnspan=5, sticky=tk.NW)
        yscroll2.grid(row=9, column=4, sticky=tk.N+tk.S+tk.E)
        xscroll2.grid(row=10, column=0, columnspan=5, sticky=tk.E+tk.W)
        listbox2.configure(yscrollcommand=yscroll2.set,xscrollcommand=xscroll2.set)
    if close == 1:
        try:
            count = listbox2.size()
            # delete conten of listbox 2
            listbox2.delete(0,count)
            listbox2.grid_remove()
            yscroll2.grid_remove()
            xscroll2.grid_remove()
        except BaseException, err:
            print time.ctime()+': sec_db: '+str(err)
            pass

def geocode_worker(lat_v,lon_v):
    global traffic, address
    try:
        url = 'http://maps.google.com/maps/geo?output=xml&oe=utf-8&ll='+str(lat_v)+','+str(lon_v)
        url = url.encode('utf-8')
        data = urllib.urlopen(url)
        xmldat = data.read()
        traffic += len(xmldat)/1000
        dom = xml.dom.minidom.parseString(xmldat)#.encode('utf-8'))
        status = dom.getElementsByTagName('code')[0].childNodes[0].nodeValue
        if status == '200':
            address = dom.getElementsByTagName('address')[0].childNodes[0].nodeValue
        else:
            address = u'N/A'
        return address
    except BaseException, err:
        address = u'N/A'
        return address
        print time.ctime()+': rev_geo: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def geocodes(event,trigger=0):
    global address, mode, defaultencoding
    try:
        data = ''
        index = listbox1.curselection()[0]
        data = listbox1.get(index)
        data = data.split(' | ')
        if mode == 'clf':
            if data[4].find('LAT') < 0 and data[4].find('NaN') < 0:
                address = geocode_worker(str(float(data[4])),str(float(data[5])))
            else:
                address = u'N/A'
        elif mode == 'wlan':
            if data[1].find('NaN') < 0 and data[1].find('LAT') < 0:
                address = geocode_worker(str(float(data[1])),str(float(data[2])))
            else:
                address = u'N/A'
        elif mode == 'wlan_log':
            if data[5].find('n/a') < 0 and data[5].find('LAT') < 0:
                address = geocode_worker(str(float(data[5])),str(float(data[6])))
            else:
                address = u'N/A'
        elif mode == 'net_log':
            if data[10].find('n/a') < 0 and data[10].find('LAT') < 0:
                address = geocode_worker(str(float(data[10])),str(float(data[9])))
            else:
                address = u'N/A'
        elif mode == 'blue':
            if data[1].find('NaN') < 0 and data[1].find('LAT') < 0:
                address = geocode_worker(str(float(data[1])),str(float(data[2])))
            else:
                address = u'N/A'
        elif mode == 'kismet':
            if data[32].find('Na') < 0 and data[32].find('Lat') < 0:
                address = geocode_worker(str(float(data[32])),str(float(data[33])))
            else:
                address = u'N/A'
        labels('<Button-1>')
        if mode == 'clf' and (address <> u'N/A') and trigger ==0:
            address_string = address
            mess = ('Replace cell-description with following string?\r\n'+
                    address_string)
            if easygui.ccbox(msg=mess, title="Lookup successful",choices=('Yes', 'No')):
                listbox1.delete(index)
                data[7] = address_string
                data[7] = data[7].ljust(50)
                newtext = ' | '.join(data)
                listbox1.insert(index,newtext)
            else:
                pass
    except IndexError:
        index = tk.END
        easygui.msgbox(msg="Open a database first AND select a listentry!", title="Error!", ok_button="OK")


def fetch_latlon(bytestring):
    global url, traffic
    try:
        user_agent = 'Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaN95_8GB/20.0.016; Profile/MDIP-2.0 Configuration/CLDC-1.1 )'
        headers = { 'User-Agent' : user_agent, "Content-type": "application/binary", "Connection": "close"}
        url = url.encode('utf-8')
        req = urllib2.Request(url, bytestring, headers)
        resp = urllib2.urlopen(req)
        response = resp.read()
        traffic += len(response)/1000
        return response
    except BaseException, err:
        print time.ctime()+': fetch_latlon: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def req_f(mcc, mnc, lac, cid, attempt_short_cid):
    try:
        if cid > 65536:
            network = 5
        else:
            network = 3
        if attempt_short_cid:
            cid &= 65536    
        return pack('>BBBBBBBBBBBBBBBBBLLLHLLLLLL', 0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,27,mnc, mcc, network, 0, cid, lac, mnc, mcc, 0, 0)
    except BaseException, err:
        print time.ctime()+': req_f: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def cell_location(cid,lac,mnc,mcc):
    global mode, address
    try:
        packed = req_f(mcc,mnc,lac,cid,False)
        res = fetch_latlon(packed)
        result, = unpack('>L', res[3:7]) 
        if result== 0:
            result, lat, lon, hpe = unpack('>LllL', res[3:19])
            a = lat/1000000.
            b = lon/1000000.
            geocode_worker(a,b)
            mess = ('According to Googles database, the cell-tower is located at:\n'
                    'Latitude %.6f\n' % float(a) +
                    'Longitude %.6f\n' % float(b) +'\n'+
                    '('+address+')\r\n'+
                    'Replace current coordinates?')
            if easygui.ccbox(msg=mess, title="Lookup successful",choices=('Yes', 'No')):
                # get selected line index
                index = listbox1.curselection()[0]
                # get the line's text
                seltext = listbox1.get(index)
                listbox1.delete(index)
                text_list = seltext.split(' | ')
                if mode == 'clf':
                    text_list[4] = '%.6f ' % float(a)
                    text_list[5] = '%.6f ' % float(b)
                    text_list[6] = '1'
                    text_list[4] = text_list[4].ljust(9)
                    text_list[5] = text_list[5].ljust(9)
                    text_list[6] = text_list[6].ljust(3)
                elif mode == 'wlan':
                    text_list[1] = '%.6f ' % float(a)
                    text_list[2] = '%.6f   ' % float(b)
                    text_list[1] = text_list[1].ljust(9)
                    text_list[2] = text_list[2].ljust(9)
                seltext = ' | '.join(text_list)
                listbox1.insert(index,seltext)
                listbox1.activate(index)
                if address <> u'N/A':
                    address_string = address
                    mess = ('Replace cell-description with following string?\r\n'+
                        address_string)
                    if easygui.ccbox(msg=mess, title="Lookup successful",choices=('Yes', 'No')):
                        # get the line's text
                        seltext = listbox1.get(index)
                        listbox1.delete(index)
                        data = seltext.split(' | ')
                        data[7] = address_string
                        data[7] = data[7].ljust(50)
                        newtext = ' | '.join(data)
                        listbox1.insert(index,newtext)
                    else:
                        pass
            else:
                pass
        else:
            easygui.msgbox(msg="Cell-Tower not in Google-database!", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': cell_location: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")

def get_cell_location(event):
    global mode
    if mode == 'clf':
        try:
            data = ''
            index = listbox1.curselection()[0]
            data = listbox1.get(index)
            if data.find('LAT') < 0 and data[62:63].find('0') == 0:
                MNC = int(data[:3])
                MCC = int(data[3:5])
                CID = int(data[10:17])
                LAC = int(data[18:24])
                cell_location(CID,LAC,MNC,MCC)
            else:
                easygui.msgbox(msg="RAT != 0, no need to lookup data.\r\nOR\r\nFirst line selected - no lookup possible!", title="Error!", ok_button="OK")
        except IndexError:
            index = tk.END
            easygui.msgbox(msg="Open a database first AND select a listentry!", title="Error!", ok_button="OK")
    elif mode == 'wlan':
        try:
            data = ''
            index = listbox1.curselection()[0]
            data = listbox1.get(index)
            if data.find('LAT') < 0 and data.find('NaN') > 0 and data[33:48].isdigit() == True:
                celldata = data[33:48]
                MNC = int(celldata[:3])
                MCC = int(celldata[3:5])
                CID = int(celldata[10:15])
                LAC = int(celldata[5:10])
                cell_location(CID,LAC,MNC,MCC)
            else:
                easygui.msgbox(msg="No cell-tower-lookup possible!", title="Error!", ok_button="OK")
        except IndexError:
            index = tk.END
            easygui.msgbox(msg="Open a database first AND select a listentry!", title="Error!", ok_button="OK")
    else:
        pass
    labels('<Button-1>')

def get_cell_location_batch(event):
    global mode, string, string2
    entry = 1
    if mode <> 'clf':
        pass
    else:
        entries = listbox1.size()
        while entry < entries:
            try:
                data = ''
                index = entry
                data = listbox1.get(index)
                if data.find('LAT') < 0 and data[62:63].find('0') == 0:
                    MNC = int(data[:3])
                    MCC = int(data[3:5])
                    CID = int(data[10:17])
                    LAC = int(data[18:24])
                    packed = req_f(MCC,MNC,LAC,CID,False)
                    res = fetch_latlon(packed)
                    result, = unpack('>L', res[3:7])
                    if result== 0:
                        result, lat, lon, hpe = unpack('>LllL', res[3:19])
                        a = lat/1000000.
                        b = lon/1000000.
                        if (-90 < a < 90) and (-180 < b < 180):
                            adresse = geocode_worker(a,b)
                            mess = ('MNC: '+str(MNC)+' MCC: '+str(MCC)+' CID: '+str(CID)+' LAC: '+str(LAC)+'\r\n'
                                    'Line: '+str(entry)+'\r\n'
                                    'According to Googles database, the cell-tower is located at:\n'
                                    'Latitude %.6f\n' % float(a) +
                                    'Longitude %.6f\r\n' % float(b) +
                                    'Description:\n'+adresse+'\r\n'+
                                    'Replace current coordinates and description?')
                            choice = easygui.buttonbox(msg=mess, title="Lookup successful",choices=('Yes','Only coordinates','No', 'Abort'))
                            if choice == 'Yes':
                                address_string = adresse
                                # get the line's text
                                seltext = listbox1.get(index)
                                listbox1.delete(index)
                                text_list = seltext.split(' | ')
                                text_list[4] = '%.6f ' % float(a)
                                text_list[5] = '%.6f ' % float(b)
                                text_list[6] = '1'
                                text_list[4] = text_list[4].ljust(9)
                                text_list[5] = text_list[5].ljust(9)
                                text_list[6] = text_list[6].ljust(3)
                                text_list[7] = address_string
                                text_list[7] = text_list[7].ljust(50)
                                seltext = ' | '.join(text_list)
                                listbox1.insert(index,seltext)
                                entry += 1
                            elif choice == 'Only coordinates':
                                # get the line's text
                                seltext = listbox1.get(index)
                                listbox1.delete(index)
                                text_list = seltext.split(' | ')
                                text_list[4] = '%.6f ' % float(a)
                                text_list[5] = '%.6f ' % float(b)
                                text_list[6] = '1'
                                text_list[4] = text_list[4].ljust(9)
                                text_list[5] = text_list[5].ljust(9)
                                text_list[6] = text_list[6].ljust(3)
                                seltext = ' | '.join(text_list)
                                listbox1.insert(index,seltext)
                                entry += 1    
                            elif choice == 'No':
                                entry += 1
                                pass
                            else:
                                break
                            labels('')
                        else:
                            entry += 1
                    else:
                        entry += 1
                        pass
                else:
                    entry += 1
                    pass
            except IndexError:
                index = tk.END
                easygui.msgbox(msg="Open a database first AND select a listentry!", title="Error!", ok_button="OK")
        easygui.msgbox(msg="Lookup finished... :-)\r\nChecked "+str(entry)+' lines.', title="Lookup finished", ok_button="OK")

def get_image(event):
    global homedir, tk, traffic
    lat=0.0
    lon=0.0
    try:
        data = ''
        index = listbox1.curselection()[0]
        data = listbox1.get(index)
        data = data.split(' | ')
        if mode == 'clf':
            if data[4].find('LAT') < 0 and data[4].find('NaN') < 0:
                lat = float(data[4])
                lon = float(data[5])
            else:
                lat = str(0.0)
                lon = str(0.0)
        elif mode == 'wlan':
            if data[1].find('NaN') < 0 and data[1].find('LAT') < 0:
                lat = float(data[1])
                lon = float(data[2])
            else:
                lat = str(0.0)
                lon = str(0.0)
        elif mode == 'wlan_log':
            if data[5].find('n/a') < 0 and data[5].find('LAT') < 0:
                lat = float(data[5])
                lon = float(data[6])
            else:
                lat = str(0.0)
                lon = str(0.0)
        elif mode == 'net_log':
            if data[10].find('n/a') < 0 and data[10].find('LAT') < 0:
                lat = float(data[10])
                lon = float(data[9])
            else:
                lat = str(0.0)
                lon = str(0.0)
        elif mode == 'blue':
            if data[1].find('NaN') < 0 and data[1].find('LAT') < 0:
                lat = float(data[1])
                lon = float(data[2])
            else:
                lat = str(0.0)
                lon = str(0.0)
        elif mode == 'kismet':
            if data[32].find('Na') < 0 and data[32].find('Lat') < 0:
                lat = float(data[32])
                lon = float(data[33])
            else:
                lat = str(0.0)
                lon = str(0.0)
        if str(lat) <> '0.0':
            url = 'http://maps.google.com/staticmap?zoom=16&size=640x640&markers='+str(lat)+','+str(lon)+'&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSsTL4WIgxhMZ0ZK_kHjwHeQuOD4xQJpBVbSrqNn69S6DOTv203MQ5ufA'
            filename_v = homedir+'position.gif'
            urllib.urlretrieve(url,filename_v)
            traf = float(os.path.getsize(filename_v))
            traffic = float(traffic)+(traf/1000)
            top_map = tk.Toplevel(root)
            top_map.iconbitmap(os.getcwd()+os.sep+'icons'+os.sep+'multiicon.ico')
            top_map.title("Map of selected listentry")
            map_img=tk.PhotoImage(file=filename_v)
            pic_label = tk.Label(top_map,image=map_img)
            pic_label.image = map_img # keep a reference!
            pic_label.pack()
            close_b = tk.Button(top_map, text="Close", command=top_map.destroy)
            close_b.pack()
            #os.startfile(filename_v)
            labels('<Button-1>')
        else:
            easygui.msgbox(msg="No valid coordinates found.", title="Error!", ok_button="OK")
    except BaseException, err:
        print time.ctime()+': get_image: '+str(err)
        easygui.msgbox(msg="An error occured! Check stdout.log file!", title="Error!", ok_button="OK")
        pass

def read_data(file_var):
    global defaultencoding
    fin = codecs.open(file_var, "rb", defaultencoding)
    try:
        ap_list = fin.readlines()
    except BaseException, err:
        print time.ctime()+': read_data: '+str(err)+' -> '+str(err.args[1][err.args[2]:err.args[3]])
        if err.args[0] == 'utf8':
            easygui.msgbox(msg="The file you have opened seems not to be UTF-8 encoded!\r\nSwitching to iso-8859-1!\r\nCheck stdout.log file!", title="Error!", ok_button="OK")
            defaultencoding = 'iso-8859-1'
            fin = codecs.open(file_var, "rb", defaultencoding)
            try:
                ap_list = fin.readlines()
            except BaseException, err:
                print time.ctime()+': read_data: '+str(err)
                easygui.msgbox(msg="Couldn't import Data correctly. Check the stdout.log file!", title="Error!", ok_button="OK")
                pass
    fin.close()
    ap_list = convert_list_2_text(ap_list)
    return ap_list

def convert_list_2_text(ap_list):
    global mode, clf_header, wlan_header, bt_header, wlog_header, netlog_header, kismet_header
    if ap_list[0].find('cell') > 0:
        mode = 'clf'
        clf_header = ap_list[0]
        ap_list[0] = ' MCC+MNC;CID;LAC;RNC;LAT;LON;RAT;DESCRIPTION;RFU'
    elif ap_list[0].find('S);BSSID') > 0:
        mode = 'wlan_log'
        wlog_header = ap_list[0]
        if wlog_header[0] <> ' ':
            ap_list[0] = ' '+wlog_header
    elif ap_list[0].find('etwork;NetType') > 0:
        mode = 'kismet'
        kismet_header = ap_list[0]
        if kismet_header[0] <> ' ':
            ap_list[0] = ' '+kismet_header
    elif ap_list[0].find('S);CID') > 0:
        mode = 'net_log'
        netlog_header = ap_list[0]
        if netlog_header[0] <> ' ':
            ap_list[0] = ' '+netlog_header
    elif ap_list[0].find('Class ID') > 0:
        mode = 'blue'
        bt_header = ap_list[0]
        if bt_header[0] <> ' ':
            ap_list[0] = ' '+bt_header
    elif ap_list[0].find('SSID;Crypt;Beacon I') > 0:
        mode = 'wlan'
        wlan_header = ap_list[0]
        if wlan_header[0] <> ' ':
            ap_list[0] = ' ' +wlan_header[wlan_header.find('B'):]
    else:
        mode = ''
        easygui.msgbox(msg="Couldn't detect filetype.", title="Error!", ok_button="OK")
    # strip the trailing newline char
    ap_list = [ap.rstrip() for ap in ap_list]
    ap_list = [ap.split(';') for ap in ap_list]
    try:
        if mode == 'clf':
            for i in range(len(ap_list)):
                if len(ap_list[i][4]) == 0:
                    ap_list[i][4] = 'NaN' 
                if len(ap_list[i][5]) == 0:
                    ap_list[i][5] = 'NaN'
                ap_list[i][0] = ap_list[i][0].ljust(8) # MCC+MNC
                ap_list[i][1] = ap_list[i][1].ljust(5) # CID
                ap_list[i][2] = ap_list[i][2].ljust(5) # LAC
                ap_list[i][3] = ap_list[i][3].ljust(5) # RNC
                ap_list[i][4] = ap_list[i][4].ljust(10)# LAT
                ap_list[i][5] = ap_list[i][5].ljust(11)# LON
                ap_list[i][6] = ap_list[i][6].ljust(3) # RAT
                ap_list[i][7] = ap_list[i][7].ljust(50)# DESCR
                ap_list[i][8] = ap_list[i][8].ljust(3) # RFU
        elif mode == 'wlan':
            #print 'ljust\r\n'
            #counter = 0
            for i in range(len(ap_list)):
                #counter += 1
                ap_list[i][0] = ap_list[i][0].ljust(17)# BSSID
                ap_list[i][1] = ap_list[i][1].ljust(10)# LAT
                ap_list[i][2] = ap_list[i][2].ljust(11)# LON
                ap_list[i][3] = ap_list[i][3].ljust(32)# SSID
                ap_list[i][4] = ap_list[i][4].ljust(6) # Crypt
                ap_list[i][5] = ap_list[i][5].ljust(15)# Beacon Interval
                ap_list[i][6] = ap_list[i][6].ljust(15)# Connection Mode
                ap_list[i][7] = ap_list[i][7].ljust(7) # Channel
                ap_list[i][8] = ap_list[i][8].ljust(4) # RXL
                ap_list[i][9] = ap_list[i][9].ljust(10)# Date
                ap_list[i][10] = ap_list[i][10].ljust(8)#Time
                #print 'Successfully imported AP: '+str(counter)
            #counter = 0
        elif mode == 'net_log':
            for i in range(len(ap_list)):
                ap_list[i][0] = ap_list[i][0].ljust(13) # Date (Y/M/D)
                ap_list[i][1] = ap_list[i][1].ljust(12) # Time (H:M:S
                ap_list[i][2] = ap_list[i][2].ljust(6)  # CID
                ap_list[i][3] = ap_list[i][3].ljust(5)  # LCID
                ap_list[i][4] = ap_list[i][4].ljust(5)  # LAC
                ap_list[i][5] = ap_list[i][5].ljust(3)  # MCC
                ap_list[i][6] = ap_list[i][6].ljust(3)  # MNC
                ap_list[i][7] = ap_list[i][7].ljust(3)  # RNC
                ap_list[i][8] = ap_list[i][8].ljust(4)  # RXL
                ap_list[i][9] = ap_list[i][9].ljust(11) # LON
                ap_list[i][10] = ap_list[i][10].ljust(10)#LAT
                ap_list[i][11] = ap_list[i][11].ljust(5)# SPEED
                ap_list[i][12] = ap_list[i][12].ljust(8)# DISTANCE
        elif mode == 'wlan_log':
            for i in range(len(ap_list)):
                ap_list[i][0] = ap_list[i][0].ljust(13) # Date (Y/M/D)
                ap_list[i][1] = ap_list[i][1].ljust(12) # Time (H:M:S
                ap_list[i][2] = ap_list[i][2].ljust(17) # BSSID
                ap_list[i][3] = ap_list[i][3].ljust(32) # SSID
                ap_list[i][4] = ap_list[i][4].ljust(4)  # RXL
                ap_list[i][5] = ap_list[i][5].ljust(10) # LAT
                ap_list[i][6] = ap_list[i][6].ljust(11) # LON
        elif mode == 'blue':
            for i in range(len(ap_list)):
                ap_list[i][0] = ap_list[i][0].ljust(17) # MAC
                ap_list[i][1] = ap_list[i][1].ljust(10) # LAT
                ap_list[i][2] = ap_list[i][2].ljust(11) # LON
                ap_list[i][3] = ap_list[i][3].ljust(32) # NAME
                ap_list[i][4] = ap_list[i][4].ljust(8) # Class ID
                ap_list[i][5] = ap_list[i][5].ljust(10) # Date
                ap_list[i][6] = ap_list[i][6].ljust(8) # Time
                ap_list[i][7] = ap_list[i][7].ljust(24) # Class
        elif mode == 'kismet':
            for i in range(len(ap_list)):
                ap_list[i][0] = ap_list[i][0].ljust(8) # Network
                ap_list[i][1] = ap_list[i][1].ljust(14) # NetType
                ap_list[i][2] = ap_list[i][2].ljust(32) # ESSID
                ap_list[i][3] = ap_list[i][3].ljust(17) # BSSID
                ap_list[i][4] = ap_list[i][4].ljust(4) # Info
                ap_list[i][5] = ap_list[i][5].ljust(7) # Channel
                ap_list[i][6] = ap_list[i][6].ljust(7) # Cloaked
                ap_list[i][7] = ap_list[i][7].ljust(10) # Encryption
                ap_list[i][8] = ap_list[i][8].ljust(9) # Decrypted
                ap_list[i][9] = ap_list[i][9].ljust(7) # MaxRate
                ap_list[i][10] = ap_list[i][10].ljust(11) # MaxSeenRate
                ap_list[i][11] = ap_list[i][11].ljust(6) # Beacon
                ap_list[i][12] = ap_list[i][12].ljust(3) # LLC
                ap_list[i][13] = ap_list[i][13].ljust(4) # Data
                ap_list[i][14] = ap_list[i][14].ljust(5) # Crypt
                ap_list[i][15] = ap_list[i][15].ljust(4) # Weak
                ap_list[i][16] = ap_list[i][16].ljust(5) # Total
                ap_list[i][17] = ap_list[i][17].ljust(7) # Carrier
                ap_list[i][18] = ap_list[i][18].ljust(8) # Encoding
                ap_list[i][19] = ap_list[i][19].ljust(23) # FirstTime
                ap_list[i][20] = ap_list[i][20].ljust(23) # LastTime
                ap_list[i][21] = ap_list[i][21].ljust(11) # BestQUality
                ap_list[i][22] = ap_list[i][22].ljust(10) # BestSignal
                ap_list[i][23] = ap_list[i][23].ljust(9) # BestNoise
                ap_list[i][24] = ap_list[i][24].ljust(10) # GPSMinLat
                ap_list[i][25] = ap_list[i][25].ljust(11) # GPSMinLon
                ap_list[i][26] = ap_list[i][26].ljust(9) # GPSMinAlt
                ap_list[i][27] = ap_list[i][27].ljust(9) # GPSMinSpd
                ap_list[i][28] = ap_list[i][28].ljust(10) # GPSMaxLat
                ap_list[i][29] = ap_list[i][29].ljust(11) # GPSMaxLon
                ap_list[i][30] = ap_list[i][30].ljust(9) # GPSMaxAlt
                ap_list[i][31] = ap_list[i][31].ljust(9) # GPSMaxSpd
                ap_list[i][32] = ap_list[i][32].ljust(10) # GPSBestLat
                ap_list[i][33] = ap_list[i][33].ljust(11) # GPSBestLon
                ap_list[i][34] = ap_list[i][34].ljust(10) # GPSBestAlt
                ap_list[i][35] = ap_list[i][35].ljust(8) # DataSize
                ap_list[i][36] = ap_list[i][36].ljust(6) # IPType
                ap_list[i][37] = ap_list[i][37].ljust(16) # IP
                
    except BaseException, err:
        print time.ctime()+': convert_list_2_text: '+str(err)
        easygui.msgbox(msg="Couldn't import Data correctly. Check the stdout.log file!", title="Error!", ok_button="OK")
        pass
    return ap_list      

def open_file(event):
    global listbox1, database, filename, backup_list
    try:
        database = askopenfilename(filetypes=[("All files","*"),("Textfiles","*.txt"),("CLF-files","*.clf")])
        if database == '':
            pass
        else:
            filename = database[database.rfind('/')+1:-4]
            count = listbox1.size()
            listbox1.delete(0,count)
            aps = read_data(database)
            # load the listbox with data
            for item in aps:
                listbox1.insert(tk.END, ' | '.join(item))
                backup_list.append(' | '.join(item))
            labels('<Button-1>')
    except BaseException, err:
        print time.ctime()+': open_file: '+str(err)
        easygui.msgbox(msg="Couldn't import Data. Check the stdout.log file!", title="Error!", ok_button="OK")
        pass

def about():
    global title
    text = (title[:17]+'\n'
            'Version '+title[19:24]+'\n'
            'November 17th, 2008\n'
            '\n'
            'by Daniel Perna\n'
            'http://www.daniel-perna.de/python.htm\n\n'
            "Geocode-functionality and cell-tower-lookup may violate Google's terms of use.\n"
            'Use at OWN risk!')
    easygui.msgbox(text,title="About")
    
def help(event):
    global helpfile
    try:
        os.startfile(helpfile)
    except BaseException, err:
        print time.ctime()+': help: '+str(err)
        easygui.msgbox(msg="Couldn't open helpfile. Check the stdout.log file!", title="Error!", ok_button="OK")
        pass

def check_mode(par):
    global mode
    if par <> mode:
        return 'disabled'
    else:
        return 'normal'

def toggle_enc(event):
    global defaultencoding
    if defaultencoding == 'utf-8':
        defaultencoding = 'iso-8859-1'
    elif defaultencoding == 'iso-8859-1':
        defaultencoding = 'utf-8'
    labels('<Button-1>')

root = tk.Tk()
#root.minsize(width=802, height=515)
#root.maxsize(width=802, height=515)
root.resizable(width=False,height=False)
root.tk_focusFollowsMouse()
root.iconbitmap(os.getcwd()+os.sep+'icons'+os.sep+'multiicon.ico')
#root.columnconfigure(0, minsize=50, weight=1)
#root.rowconfigure(0, weight=1)
#root.columnconfigure(1, minsize=17, weight=1)
#root.rowconfigure(1, weight=1)
#root.columnconfigure(2, weight=1)
#root.rowconfigure(2, weight=1)

#toolbar frame1
toolbar = tk.Frame(root)
toolbar.grid(row=0, column=0, sticky=tk.NW)

open_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'open.gif')
open_b=tk.Button(toolbar, image=open_im,command=lambda: open_file('<KeyPress-o'))
open_b.pack(side=tk.LEFT)
open_t = ToolTip(open_b, follow_mouse=1, text="Open file",delay=800)

save_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'save.gif') 
save_b=tk.Button(toolbar, state='disabled', image=save_im,command=lambda: save_list('<KeyPress-s')) 
save_b.pack(side=tk.LEFT)
save_t = ToolTip(save_b, follow_mouse=1, text="Save file",delay=800)

kml_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'kml.gif') 
kml_b=tk.Button(toolbar, image=kml_im,command=export_kml) 
kml_b.pack(side=tk.LEFT)
kml_t = ToolTip(kml_b, follow_mouse=1, text="Export to KML",delay=800)

separator=tk.PhotoImage(file=homedir+'icons'+os.sep+'separator.gif') 
sep_b1=tk.Button(toolbar, image=separator,bd=0,relief='flat') 
sep_b1.pack(side=tk.LEFT)

del_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'delete.gif') 
del_b=tk.Button(toolbar, image=del_im,command=lambda:delete_item('<Delete>')) 
del_b.pack(side=tk.LEFT)
del_t = ToolTip(del_b, follow_mouse=1, text="Delete active listentry",delay=800)

add_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'append.gif') 
add_b=tk.Button(toolbar, image=add_im,command=add_item) 
add_b.pack(side=tk.LEFT)
add_t = ToolTip(add_b, follow_mouse=1, text="Append to list",delay=800)

replace_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'replace.gif') 
replace_b=tk.Button(toolbar, image=replace_im,command=lambda:set_list('')) 
replace_b.pack(side=tk.LEFT)
replace_t = ToolTip(replace_b, follow_mouse=1, text="Replace active listentry",delay=800)

sort_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'sort.gif') 
sort_b=tk.Button(toolbar, image=sort_im,command=sort_list) 
sort_b.pack(side=tk.LEFT)
sort_t = ToolTip(sort_b, follow_mouse=1, text="Sort list",delay=800)

sep_b2=tk.Button(toolbar, image=separator,bd=0,relief='flat') 
sep_b2.pack(side=tk.LEFT)

addr_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'address.gif') 
addr_b=tk.Button(toolbar, image=addr_im,command=lambda: geocodes('<KeyPress-a>')) 
addr_b.pack(side=tk.LEFT)
addr_t = ToolTip(addr_b, follow_mouse=1, text="Get address",delay=800)

map_im=tk.PhotoImage(file=homedir+'icons'+os.sep+'map.gif') 
map_b=tk.Button(toolbar, image=map_im,command=lambda: get_image('<KeyPress-m>')) 
map_b.pack(side=tk.LEFT)
map_t = ToolTip(map_b, follow_mouse=1, text="Show on map",delay=800)

#frame2
mainframe = tk.Frame(root)
mainframe.grid(row=1,column=0)
# create the listbox (note that size is in characters)
listbox1 = tk.Listbox(mainframe, width=98, height=20, font=('courier','10'))
listbox1.grid(row=0, column=0, columnspan=5, sticky=tk.NW)

# create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(mainframe,command=listbox1.yview, orient=tk.VERTICAL)
yscroll.grid(row=0, column=4, sticky=tk.N+tk.S+tk.E)
xscroll = tk.Scrollbar(mainframe,command=listbox1.xview, orient=tk.HORIZONTAL)
xscroll.grid(row=1, column=0, columnspan=5, sticky=tk.E+tk.W)
listbox1.configure(yscrollcommand=yscroll.set,xscrollcommand=xscroll.set)

# create second listbox but don't grid it
listbox2 = tk.Listbox(mainframe, width=98, height=10, font=('courier','10'))
yscroll2 = tk.Scrollbar(mainframe,command=listbox2.yview, orient=tk.VERTICAL)
xscroll2 = tk.Scrollbar(mainframe,command=listbox2.xview, orient=tk.HORIZONTAL)

# use entry widget to display/edit selection
enter1 = tk.Entry(mainframe, width=133, bg='white')
enter1.insert(0, "Enter own data here (don't forget to use the right number of | ). Edit existing entry by double-clicking it.")
enter1.grid(row=6, column=0, columnspan=6)
# pressing the return key will update edited line
enter1.bind('<Return>', set_list)
# or double click left mouse button to update line
#enter1.bind('<Double-1>', set_list)

# button to add a line to the listbox
#addline_button = tk.Button(root, text='Add text from textfield below', command=add_item)
#addline_button.grid(row=5, column=4, sticky=tk.E)

def labels(event):
    global mode, title, traffic
    # Titelleiste
    root.title(title+database[database.rfind('/')+1:])
    #streetlabel
    streetlabel = tk.Label (mainframe, anchor=tk.W, width=80, text=u'Address:    '+address)
    streetlabel.grid(row=3, column=0, sticky=tk.W)
    #traffic
    traflabel = tk.Label (mainframe, anchor=tk.E, width=20, text=u'Traffic: %0.2f KB'%float(traffic*1000/1024))
    traflabel.grid(row=4, column=4, sticky=tk.E)
    #encoding
    enclabel = tk.Label (mainframe, anchor=tk.W, width=20, text=u'Encoding: '+defaultencoding)
    enclabel.grid(row=4, column=0, sticky=tk.W)
    #current database
    currfile = tk.Label (mainframe, anchor=tk.W, width=80, text=u'Datafile:    '+database)
    currfile.grid(row=2, column=0, sticky=tk.W)
    if mode == '':
        filemenu.entryconfigure(1, state=(lambda m: check_mode(m))(' '))# Save as
        #filemenu.entryconfigure(3, state=(lambda m: check_mode(m))(' '))# KML-Export
        menubar.entryconfigure(2, state=(lambda m: check_mode(m))(' ')) # Edit Menu
        save_b.configure(state=(lambda m: check_mode(m))(' '))
        filemenu.entryconfigure(5, state=(lambda m: check_mode(m))(' '))# KML-Export
        kml_b.configure(state=(lambda m: check_mode(m))(' '))#kml button
        del_b.configure(state=(lambda m: check_mode(m))(' '))#del button
        add_b.configure(state=(lambda m: check_mode(m))(' '))#add button
        replace_b.configure(state=(lambda m: check_mode(m))(' '))#replace button
        sort_b.configure(state=(lambda m: check_mode(m))(' '))#sort button
        map_b.configure(state=(lambda m: check_mode(m))(' '))#map button
        addr_b.configure(state=(lambda m: check_mode(m))(' '))#addr button
    else:
        filemenu.entryconfigure(1, state=(lambda m: check_mode(m))(mode))# Save as
        #filemenu.entryconfigure(3, state=(lambda m: check_mode(m))(mode))# KML-Export
        menubar.entryconfigure(2, state=(lambda m: check_mode(m))(mode)) # Edit-Menu
        save_b.configure(state=(lambda m: check_mode(m))(mode))
        filemenu.entryconfigure(5, state=(lambda m: check_mode(m))(mode))# KML-Export
        kml_b.configure(state=(lambda m: check_mode(m))(mode))#kml button
        del_b.configure(state=(lambda m: check_mode(m))(mode))#del button
        add_b.configure(state=(lambda m: check_mode(m))(mode))#add button
        replace_b.configure(state=(lambda m: check_mode(m))(mode))#replace button
        sort_b.configure(state=(lambda m: check_mode(m))(mode))#sort button
        map_b.configure(state=(lambda m: check_mode(m))(mode))#map button
        addr_b.configure(state=(lambda m: check_mode(m))(mode))#addr button
    if mode <> 'wlan' and mode <> 'blue' and mode <> 'wlan_log' and mode <> 'clf' and mode <> 'net_log':
        menubar.entryconfigure(2, state=(lambda m: check_mode(m))(' ')) # Edit Menu
        del_b.configure(state=(lambda m: check_mode(m))(' '))#del button
        add_b.configure(state=(lambda m: check_mode(m))(' '))#add button
        sort_b.configure(state=(lambda m: check_mode(m))(' '))#sort button
    filemenu.entryconfigure(7, state=(lambda m: check_mode(m))('wlan')) # Open second database
    filemenu.entryconfigure(8, state=(lambda m: check_mode(m))('wlan')) # close second database
    menubar.entryconfigure(3, state=(lambda m: check_mode(m))('wlan'))  # WLAN Menu
    menubar.entryconfigure(4, state=(lambda m: check_mode(m))('clf'))   # CLF Menu
    menubar.entryconfigure(5, state=(lambda m: check_mode(m))('blue'))  # BT Menu
    menubar.entryconfigure(6, state=(lambda m: check_mode(m))('wlan_log'))#WLAN LOG Menu
    menubar.entryconfigure(7, state=(lambda m: check_mode(m))('net_log'))#NetLog Menu

# Menubar
menubar = tk.Menu(root)
# create a pulldown menu, and add it to the menu bar
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Open                  (CTRL+o)", command=lambda: open_file('<KeyPress-o'))
filemenu.add_command(label="Save as               (CTRL+s)", command=lambda: save_list('<KeyPress-s'))
filemenu.add_separator()
filemenu.add_command(label="Toggle Encoding          (e)", command=lambda: toggle_enc('<KeyPress-e'))
filemenu.add_separator()
filemenu.add_command(label="Export to KML   (CTRL+k)", command=export_kml)
filemenu.add_separator()
filemenu.add_command(label="Open second Database ", command=open_second_file)
filemenu.add_command(label="Close second Database", command=lambda: sec_db(1))
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="Delete selected line                                                        (Del)", command=lambda:delete_item('<Delete>'))
editmenu.add_command(label="Add text from textfield to end of list",command=add_item)
editmenu.add_command(label="Replace text from active listentry with text from textfield", command=lambda:set_list(''))
editmenu.add_separator()
editmenu.add_command(label="Sort list alphabetically", command=sort_list)
menubar.add_cascade(label="Edit",menu=editmenu)

wlanmenu = tk.Menu(menubar, tearoff=0)
wlanmenu.add_command(label="Get address                                     (a)", command=lambda: geocodes('<KeyPress-a>'))
wlanmenu.add_command(label="Lookup cell-tower coordinates    (t)", command=lambda: get_cell_location('<KeyPress-t>'))
wlanmenu.add_command(label="Show on map                                 (m)", command=lambda: get_image('<KeyPress-m>'))
wlanmenu.add_separator()
wlanfiltermenu = tk.Menu(wlanmenu, tearoff=0)
wlanmenu.add_cascade(label='Filter', menu=wlanfiltermenu)
wlanmenu.add_separator()
wlanmenu.add_command(label="Kismet - Export all", command=kismet_export)
wlanmenu.add_command(label="Kismet - Export date", command=kismet_export_today)
wlanmenu.add_separator()
wlanmenu.add_command(label="Merge Databases     ", command=merge)

menubar.add_cascade(label="WLAN", state='disabled',menu=wlanmenu)

wlancryptmenu = tk.Menu(wlanmenu, tearoff=0)
wlancryptmenu.add_command(label="Show all",command=lambda:filter_wlan((81,88),' '))
wlancryptmenu.add_command(label="Show Open",command=lambda:filter_wlan((81,88),'Open'))
wlancryptmenu.add_command(label="Show Wep",command=lambda:filter_wlan((81,88),'Wep'))
wlancryptmenu.add_command(label="Show WpaPsk",command=lambda:filter_wlan((81,88),'WpaPsk'))
wlanfiltermenu.add_cascade(label='Filter by encryption', menu=wlancryptmenu)

wlanlocmenu = tk.Menu(wlanmenu, tearoff=0)
wlanlocmenu.add_command(label="Show all",command=lambda:filter_wlan((19,20),' '))
wlanlocmenu.add_command(label="Show with coordinates",command=lambda:filter_wlan((20,29),'.'))
wlanlocmenu.add_command(label="Show NaN",command=lambda:filter_wlan((20,29),'NaN'))
wlanfiltermenu.add_cascade(label='Filter by coordinates', menu=wlanlocmenu)

wlandatemenu = tk.Menu(wlanmenu, tearoff=0)
wlandatemenu.add_command(label="Show all",command=lambda:filter_wlan((19,20),' '))
wlandatemenu.add_command(label="Show today",command=lambda:filter_wlan((144,154),time.strftime("%Y/%m/%d")))
wlandatemenu.add_command(label="Show specific date",command=lambda:filter_wlan((144,154),easygui.enterbox(msg='Enter date to show.\nFormat is: YYYY/MM/DD!', title='Enter date to show!', default=time.strftime("%Y/%m/%d"), strip=True)))
wlanfiltermenu.add_cascade(label='Filter by date', menu=wlandatemenu)

clfmenu = tk.Menu(menubar, tearoff=0)
clfmenu.add_command(label="Get address                                      (a)", command=lambda: geocodes('<KeyPress-a>'))
clfmenu.add_command(label="Lookup Cell-Tower coordinates   (t)", command=lambda: get_cell_location('<KeyPress-t>'))
clfmenu.add_command(label="Show on map                                  (m)", command=lambda: get_image('<KeyPress-m>'))
clfmenu.add_separator()
clfmenu.add_command(label="Get all Cell-Tower coordinates", command=lambda: get_cell_location_batch('<KeyPress-t>'))
menubar.add_cascade(label="CLF", state='disabled', menu=clfmenu)

btmenu = tk.Menu(menubar, tearoff=0)
btmenu.add_command(label="Get address                                      (a)", command=lambda: geocodes('<KeyPress-a>'))
btmenu.add_command(label="Show on map                                  (m)", command=lambda: get_image('<KeyPress-m>'))
menubar.add_cascade(label="BT", state='disabled', menu=btmenu)

wlogmenu = tk.Menu(menubar, tearoff=0)
wlogmenu.add_command(label="Get address                                      (a)", command=lambda: geocodes('<KeyPress-a>'))
wlogmenu.add_command(label="Show on map                                  (m)", command=lambda: get_image('<KeyPress-m>'))
#wlogmenu.add_command(label="Export to KML", command=path_kml)
menubar.add_cascade(label="WLAN Log", state='disabled', menu=wlogmenu)

netlogmenu = tk.Menu(menubar, tearoff=0)
netlogmenu.add_command(label="Get address                                      (a)", command=lambda: geocodes('<KeyPress-a>'))
netlogmenu.add_command(label="Show on map                                  (m)", command=lambda: get_image('<KeyPress-m>'))
#netlogmenu.add_command(label="Export to KML", command=path_kml)
menubar.add_cascade(label="Net Log", state='disabled', menu=netlogmenu)

helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help      (F1)", command=lambda: help('<KeyPress-F1>'))
helpmenu.add_command(label="About", command=about)
menubar.add_cascade(label="Help", menu=helpmenu)

# display the menu
root.config(menu=menubar)

listbox1.bind('<Double-Button-1>', get_list)
listbox1.bind('<KeyPress-Up>', listbox1.yview_scroll(-1,'units'))
listbox1.bind('<KeyPress-Down>', listbox1.yview_scroll(1,'units'))
listbox1.bind('<Delete>', delete_item)
root.bind_all('<KeyPress-t>', get_cell_location)
root.bind_all('<KeyPress-a>', geocodes)
root.bind_all('<KeyPress-e>', toggle_enc)
root.bind_all('<KeyPress-m>', get_image)
root.bind_all('<Control-KeyPress-k>', export_kml)
root.bind_all('<Control-KeyPress-s>', save_list)
root.bind_all('<Control-KeyPress-o>', open_file)
#root.bind_all(91, delete_item)
root.bind_all('<KeyPress-F1>', help)
labels('<Button-1>')

# polled labels
element = tk.Label (mainframe, anchor=tk.E, width=20, text='Active element: ')
element.grid(row=3, column=4, sticky=tk.E)
elementcount = tk.Label (mainframe, anchor=tk.E, width=20, text='Listelements: ')
elementcount.grid(row=2, column=4, sticky=tk.E)
lab = element
def poll():
    element.after(200, poll)
    if len(listbox1.curselection()) > 0:
        active = listbox1.curselection()[0]
        element.config(text='Active element: '+str(active))
    if listbox1.size() > 0:
        count = listbox1.size()-1
        elementcount.config(text='Listelements: '+str(count))

poll()
root.mainloop()